<template>
    <div class="base-page"  :style="{ height:screenHeight-20+'px'}">
        <div style="height:100%" class="right select-item" v-show="viewList === true">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="default" size="mini"
                            >导出</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-tree-table">
                <div class="errorMsg">
                <span >
                    系统级功能，只能查询，若需修改，请联系系统实施人员
                </span>
            </div>
            <div class="e-table  e-tree-table"  :style="{ height:screenHeight-50+'px'}">
                <el-table
                    :data="tableData"
                    style="width: 100%; margin-bottom: 20px"
                    row-key="kvId"
                    border
                    ref="tableRef"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                    :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren',
                    }"
                    lazy
                    :cell-class-name="cellClsNm"
                    @cell-mouse-enter="cellMouseEnter"
                    @cell-mouse-leave="cellMouseLeave"
                    :load="loadTableTree"
                    @expand-change="switchRow"
                    class="table"
                >
                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                    <el-table-column label="操作" fixed width="250px" align="left">
                    </el-table-column>
                    <el-table-column prop="kvDescription" fixed label="编号"> </el-table-column>
                    <el-table-column prop="kvKey" label="描述"></el-table-column>
                </el-table>
            </div>
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-if="viewList === 'add' || viewList === 'edit'">
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">外包方类型</div>
                <el-form ref="form" :model="formData" :rules="rules" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="编号：" prop="kvDescription">
                                <span>{{ formData.kvDescription }}</span>
                            </el-form-item>
                            <el-form-item label="描述：" prop="kvKey">
                                <span>{{ formData.kvKey }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="default" size="mini"
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
        <!-- 新增子级的界面 -->
        <div class="right" v-else-if="viewList === 'addChild' || viewList === 'editChild'">
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">外包方类型</div>
                <el-form ref="formRef" :model="formDataChild" :rules="rules" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="父节点编号：">
                                <span>{{ parent.kvDescription }}</span>
                            </el-form-item>
                        </el-col>
                         <el-col :span="12">
                            <el-form-item label="父节点描述：">
                                <span>{{ parent.kvKey }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="子节点编号：" prop="kvDescription">
                                <el-input v-model="formDataChild.kvDescription" placeholder="请输入编号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="子节点描述：" prop="kvKey">
                                <el-input v-model="formDataChild.kvKey" placeholder="请输入描述"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary" size="mini"
                        @click="onSaveChild"
                    >保存</el-button>
                    <el-button type="default" size="mini"
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { debounce } from '@/utils/common'
import { getSystemCurrencyTree, setCurrencyTree, deleteCurrencyTree } from '@/api/base/currency'
export default {
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            tableData: [],
            formData: {},
            formDataChild: {},
            rules: {
                kvKey: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                ],
            },
            params: {
                dicName: '',
                parentId: '',
                isEnable: false
            },
            selectData: null,
            currencyOptions: [],
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            parent: {
                kvDescription: '',
                kvKey: ''
            },
            tableView: false, //控制表格是否重新渲染
            mapData: {}, //存储当前节点信息
            MouseEnterId: 0,
            isDelete: false
        }
    },
    computed: {
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 280) + 'px'
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        }
    },
    mounted () {
        this.getTableData()

        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        cellMouseEnter (row) {
            this.MouseEnterId = row.kvId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        getTableData () {
            this.params.dicName = '外包方类型'
            this.params.parentId = '0'
            this.tableData = []
            getSystemCurrencyTree(this.params).then(res=>{
                const fn = data =>{
                    data.forEach(item=>{
                        item.hasChildren = !item.isLeaf
                        item.isExpand = false
                    })
                    this.tableData = data
                    this.tableView = true
                }
                fn(res)
            })
        },
        //差量更新表格数据，不改变表格展开收缩状态
        getTableData1 () {
            this.params.dicName = '外包方类型'
            this.params.parentId = '0'
            getSystemCurrencyTree(this.params).then(res=>{
                const fn = data =>{
                    data.forEach(item=>{
                        item.hasChildren = !item.isLeaf
                        item.isExpand = false
                    })
                    this.tableData.push(data[data.length - 1])
                    this.switchStatus()
                    this.tableView = true
                }
                fn(res)
            })
        },
        loadTableTree (tree, treeNode, resolve) {
            if(treeNode.children.length > 0) {
                setTimeout(()=>{
                    this.$refs.tableRef.toggleRowExpansion(tree, false)
                }, 10)
            }
            this.params.parentId = tree.kvId
            this.mapData[tree.kvId] = { tree, treeNode, resolve }
            getSystemCurrencyTree(this.params).then(res=>{
                const fn = data => {
                    data = data ? data : []
                    data.forEach(item=>{
                        item.hasChildren = !item.isLeaf
                        item.isExpand = false
                    })
                    tree.children = data
                    resolve(data)
                }
                fn(res)
            })
        },
        switchStatus () {
            const fn1 = value=>{
                value.forEach(item=>{
                    setTimeout(()=>{
                        this.$refs.tableRef.toggleRowExpansion(item, item.isExpand)
                    }, 10)
                    if(item.hasChildren && item.children && item.isExpand) {
                        fn1(item.children)
                    }
                })
            }
            fn1(this.tableData)
        },
        onSelectOrg (val) {
            this.formData = {
                ...val,
                currency: 10
            }
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            this.params.dicKey = searchKey
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            this.getTableData()
        },
        goAdd () {
            // 添加顶级时，设置选中项为空
            this.selectData = null
            this.viewList = 'add'
            this.formData = {
                'kvId': '',
                'kvKey': '',
                'kvStatus': 0,
                'kvValue': '',
                'parentKvId': '0',
                'kvDescription': ''
            }
        },
        //添加子级
        addChild (row) {
            this.parent = row
            this.formDataChild = {
                'kvId': '',
                'kvKey': '',
                'kvStatus': 0,
                'kvValue': '',
                'parentKvId': '0',
                'kvDescription': ''
            }
            this.formDataChild.parentKvId = row.kvId
            if(row.isLeaf === 1 || !row.children || row.children.length === 0) {
                this.formDataChild.kvDescription = row.kvDescription + '-1'
            }else{
                const arr = row.children[row.children.length - 1].kvDescription.split('-')
                arr.splice(-1, 1, Number(arr[arr.length - 1]) + 1)
                this.formDataChild.kvDescription = arr.join('-')
            }
            this.viewList = 'addChild'
        },
        edit (row) {
            if(row.parentKvId === '0') {
                this.formData = this._.clone(row)
                this.viewList = 'edit'
            }else{
                this.formDataChild = this._.clone(row)
                this.formDataChild.dicName = '外包方类型'
                const fn = data => {
                    for(let i = 0; i < data.length; i++) {
                        if(data[i].children) {
                            if(data[i].kvId === row.parentKvId) {
                                this.parent = data[i]
                                this.viewList = 'editChild'
                                return
                            }else{
                                fn(data[i].children)
                            }
                        }
                    }
                }
                fn(this.tableData)
            }
        },
        //删除节点
        deleteEle (row) {
            row.dicName = '外包方类型'
            // this.clientPop('info', this.oneDeleteErr, ()=>{
            //     deleteCurrencyTree(row).then(()=>{
            //         this.clientPop('suc', '删除成功', ()=>{
            //             this.viewList = true
            //             this.tableView = false
            //             this.isDelete = true
            //         })
            //     })
            // })
            // 否则先提示，再删除
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作', () => {
                deleteCurrencyTree(row).then(() => {
                    this.clientPop('suc', '删除成功', () => {
                        const id = row.parentKvId
                        console.log('id: ', id)
                        if(this.mapData[id]) {
                            const { tree, treeNode, resolve } = this.mapData[id]
                            this.$set(this.$refs.tableRef.store.states.lazyTreeNodeMap, id, [])
                            // 如果还有兄弟，则重新加载父节点，否则重新加载父节点的父节点，刷新目录状态
                            // 删除后还有，所以 > 1
                            if (tree.children.length > 1) {
                                this.loadTableTree(tree, treeNode, resolve)
                            } else {
                                if (tree.parentKvId === '0') {
                                    this.getTableData()
                                } else {
                                    this.loadTableTree(this.mapData[tree.parentKvId].tree, this.mapData[tree.parentKvId].treeNode, this.mapData[tree.parentKvId].resolve)
                                }
                            }
                        } else {
                            this.getTableData()
                        }
                    })
                })
            })
        },
        //操作节点后更新父亲节点
        updateEle (id) {
            if(id === '0') {
                this.getTableData()
                return
            }
            this.params.parentId = id
            getSystemCurrencyTree(this.params).then(res=>{
                const fn = data =>{
                    data = data ? data : []
                    data.forEach(item=>{
                        item.hasChildren = !item.isLeaf
                    })
                    const fn1 = item=>{
                        for(let i = 0;i < item.length;i++) {
                            if(item[i].kvId === id) {
                                this.parent = item[i]
                                item[i].isLeaf = 0
                                item[i].children = data
                                item.isExpand = false
                                if(item[i].parentKvId === '0') {
                                    item[i].hasChildren = !this.isDelete
                                }
                                this.isDelete = false
                                return
                            }else{
                                if(item[i].children) {
                                    fn1(item[i].children)
                                }
                            }
                        }
                    }
                    fn1(this.tableData)
                    this.$set(this.$refs.tableRef.store.states.lazyTreeNodeMap, id, data)
                    // 已获取最新数据，重复获取了
                    // if(this.mapData[id]) {
                    //     const { tree, treeNode, resolve } = this.mapData[id]
                    //     this.loadTableTree(tree, treeNode, resolve)
                    // }
                    this.switchStatus()
                }
                fn(res)
            })
        },
        switchRow (row, expanded) {
            row.isExpand = expanded
        },
        onSave () {
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    this.formData.dicName = '外包方类型'
                    setCurrencyTree(this.formData).then(() => {
                        this.clientPop('suc', '保存成功', () => {
                            this.updateEle(this.formData.parentKvId)
                            this.viewList = true
                        })
                    })
                }
            })
        },
        //保存子级
        onSaveChild () {
            this.$refs['formRef'].validate(async valid => {
                if (valid) {
                    this.formDataChild.dicName = '外包方类型'
                    setCurrencyTree(this.formDataChild).then(() => {
                        this.clientPop('suc', '保存成功', () => {
                            this.updateEle(this.parent.kvId)
                            this.viewList = true
                            this.tableView = false
                        })
                    })
                }
            })
        },
        //取消
        onCancel () {
            this.viewList = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
    }
}
</script>

<style lang="scss" scoped>
.select-item {
  width: 60%;
  height: 90%;

  margin: auto;

  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .top {
    height: 50px;
    display: flex;
    justify-content: space-between;
    .info {
      width: 60px;
      height: 50px;
      line-height: 50px;
      position: relative;
      .tabs-title::before {
        content: "";
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 0px;
        top: 14px;
      }
    }
    .ipt-box {
      width: 210px;
      height: 50px;
      position: relative;
        .ipt{
            border: 0;
            width: 200px;
            height: 30px;
            border-radius: 5px;
            margin-top: 12px;
            box-sizing: border-box;
            padding-left: 20px;
            border: 1px solid #ccc;
        }
        img{
          height: 15px;
          width: 15px;
          position: absolute;
          top: 20px;
          right: 19px;
          cursor: pointer;
        }
        ::placeholder{
          padding-left: 15px;
          font-weight: 700;
        }
    }
  }
  .table {
    flex: 1;
    border-radius: 5px;
    margin-top: 10px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
::v-deep.has-gutter th {
            background: #e0e7f9 !important;
            color: #000;
          }
          ::v-deep.el-table--enable-row-hover .el-table__body tr:hover {
            font-weight: bold;
          }
          ::v-deep.el-table ::v-deep .el-table__expand-icon--expanded {
            transform: none;
          }
          ::v-deep.el-tree ::v-deep .el-tree-node__expand-icon.expanded {
            -webkit-transform: rotate(0deg);
            transform: rotate(0deg);
          }
  }
  .footer {
    height: 50px;
    display: flex;
     background-color: #eff2f6;
      .left {
      width: 60%;
      height: 50px;
    }
    .right {
      line-height: 50px;
      font-weight: 500;
      color: rgb(233, 84, 66);
      font-size: 14px;
      .colse-btn {
        background-color: #fff;
        color: #000;
      }
    }
    ::v-deep.el-button--mini {
      width: 60px;
      color: #fff;
      margin-left: 10px;
      background-color: rgb(46, 97, 215);
    }
  }
}
.e-tree-table{
    border: none;
}
.right{
    border: none;
}
::v-deep .el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(1){
            .cell{
                justify-content: flex-start;
            }
        }
    }
    ::v-deep .has-gutter{
        .cell{
            display: flex;
            align-items: center;
        }
        th:nth-child(1){
            .cell{
                text-align: left;
            }
        }
    }
</style>
